<template>
  <el-dialog
    :model-value="visible"
    title="产品详情"
    width="1000px"
    @close="handleClose"
  >
    <div v-loading="loading" class="product-detail">
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 产品图片 -->
          <div class="product-images">
            <h4>产品图片</h4>
            <div class="image-gallery">
              <el-image
                v-for="(image, index) in product.images"
                :key="index"
                :src="image"
                :preview-src-list="product.images"
                fit="cover"
                class="gallery-image"
              />
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <!-- 基本信息 -->
          <el-descriptions title="基本信息" :column="1" border>
            <el-descriptions-item label="产品名称">
              {{ product.name }}
            </el-descriptions-item>
            <el-descriptions-item label="产品分类">
              {{ product.category }}
            </el-descriptions-item>
            <el-descriptions-item label="单价">
              <span class="price">¥{{ product.unitPrice }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="制作时间">
              {{ formatTime(product.productionTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="难度等级">
              <el-rate
                v-model="product.difficulty"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}级"
              />
            </el-descriptions-item>
            <el-descriptions-item label="库存数量">
              <el-tag :type="getStockTagType(product.stock)">
                {{ product.stock }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="产品状态">
              <el-tag :type="product.status === 1 ? 'success' : 'danger'">
                {{ product.status === 1 ? '可领取' : '已下架' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 制作工具 -->
          <div class="product-tools-section">
            <h4>制作工具</h4>
            <div class="tools-container">
              <el-tag
                v-for="tool in product.tools"
                :key="tool"
                type="info"
                style="margin-right: 8px; margin-bottom: 8px"
              >
                {{ tool }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 制作演示视频 -->
      <div class="product-video" v-if="product.videoUrl">
        <h4>制作演示视频</h4>
        <div class="video-container">
          <video
            :src="product.videoUrl"
            controls
            style="width: 100%; max-width: 600px; border-radius: 8px"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
      </div>

      <!-- 配件清单 -->
      <div class="accessories-list">
        <h4>配件清单</h4>
        <el-table :data="product.accessoriesList" border size="small">
          <el-table-column prop="name" label="配件名称" width="200" />
          <el-table-column prop="quantity" label="数量" width="150" />
          <el-table-column prop="unit" label="单位" width="100" />
          <el-table-column label="备注">
            <template #default="{ row }">
              {{ getAccessoryRemark(row.name) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 产品描述 -->
      <div class="product-description">
        <h4>产品描述</h4>
        <p>{{ product.description }}</p>
      </div>

      <!-- 任务统计 -->
      <el-row :gutter="20" class="stats-section">
        <el-col :span="6">
          <el-statistic title="总领取数" :value="product.claimedCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="完成数" :value="product.completedCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="审核通过数" :value="product.approvedCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="完成率"
            :value="getCompletionRate(product.claimedCount, product.completedCount)"
            suffix="%"
            :precision="1"
          />
        </el-col>
      </el-row>

      <!-- 时间信息 -->
      <el-descriptions title="时间信息" :column="2" border style="margin-top: 20px">
        <el-descriptions-item label="创建时间">
          {{ product.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ product.updateTime }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑产品</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { productAPI } from '@/api/product'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  productId: {
    type: [String, Number],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'edit'])

// 响应式数据
const loading = ref(false)
const product = ref({})

// 格式化时间
const formatTime = (minutes) => {
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
}

// 获取配件备注
const getAccessoryRemark = (name) => {
  const remarks = {
    '红绳': '优质尼龙绳，颜色鲜艳',
    '珠子': '彩色塑料珠，多种颜色可选',
    '剪刀': '小型手工剪刀，锋利耐用',
    '胶水': '速干手工胶水',
    '弹力线': '高弹力尼龙线',
    '串珠针': '细长型，易于串珠',
    '搭扣': '金属材质，坚固耐用',
    '彩色折纸': '环保材质，色彩丰富',
    '铁丝': '软铁丝，易于造型',
    '胶带': '透明胶带，粘性强',
    '包装纸': '精美包装纸'
  }
  return remarks[name] || '优质材料'
}

// 获取完成率
const getCompletionRate = (claimed, completed) => {
  if (claimed === 0) return 0
  return ((completed / claimed) * 100).toFixed(1)
}

// 获取库存标签类型
const getStockTagType = (stock) => {
  if (stock === 0) return 'danger'
  if (stock < 50) return 'warning'
  return 'success'
}

// 获取产品详情
const fetchProductDetail = async () => {
  if (!props.productId) return

  loading.value = true
  try {
    const response = await productAPI.getDetail(props.productId)
    product.value = response.data || {}
  } catch (error) {
    console.error('获取产品详情失败:', error)
    ElMessage.error('获取产品详情失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 编辑产品
const handleEdit = () => {
  emit('edit', product.value)
  handleClose()
}

// 监听props变化
watch(() => props.visible, (visible) => {
  if (visible && props.productId) {
    fetchProductDetail()
  }
})
</script>

<style lang="scss" scoped>
.product-detail {
  .price {
    font-size: 18px;
    font-weight: 600;
    color: #f56c6c;
  }

  .product-images {
    h4 {
      margin-bottom: 12px;
      color: #2c3e50;
      font-weight: 600;
    }

    .image-gallery {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;

      .gallery-image {
        width: 100%;
        height: 150px;
        border-radius: 8px;
      }
    }
  }

  .product-tools-section {
    margin-top: 20px;

    h4 {
      margin-bottom: 12px;
      color: #2c3e50;
      font-weight: 600;
    }

    .tools-container {
      display: flex;
      flex-wrap: wrap;
    }
  }

  .product-video {
    margin: 20px 0;

    h4 {
      margin-bottom: 12px;
      color: #2c3e50;
      font-weight: 600;
    }

    .video-container {
      text-align: center;
    }
  }

  .accessories-list {
    margin: 20px 0;

    h4 {
      margin-bottom: 12px;
      color: #2c3e50;
      font-weight: 600;
    }
  }

  .product-description {
    margin: 20px 0;

    h4 {
      margin-bottom: 12px;
      color: #2c3e50;
      font-weight: 600;
    }

    p {
      line-height: 1.6;
      color: #606266;
      margin: 0;
    }
  }

  .stats-section {
    margin: 20px 0;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>